//----------------------------------------------------------------------------------------
// @Project Includes
#include "includes.h"

//----------------------------------------------------------------------------------------
// @Local Macro Define in the module
#define CD_CAN_MULTI_FRAME_TIMEOUT_MS    200    // 多帧传输超时时间(毫秒)
#define CD_CAN_RESPONSE_TIMEOUT_MS       50     // 响应超时时间(毫秒)
#define CD_UPGRADE_TIMEOUT_MS            5000   // 升级超时时间(毫秒)

// 多帧传输缓冲区
static uint8_t g_multiFrameRxBuffer[CD_MAX_MULTI_FRAME_SIZE];
static uint8_t g_multiFrameTxBuffer[CD_MAX_MULTI_FRAME_SIZE];

// 升级缓冲区
static uint8_t g_firmwareBuffer[CD_MAX_FIRMWARE_SIZE];

//----------------------------------------------------------------------------------------
// @Local Type defines in the module

//----------------------------------------------------------------------------------------
// @Global Variables define in the module
stc_cd_can_t g_stcCdCan = {0};

//----------------------------------------------------------------------------------------
// @Prototypes of functions in the module
static void cd_can_process_read_request(uint16_t reg_addr, uint16_t reg_count, uint8_t frame_index, uint8_t *data);
static void cd_can_process_write_request(uint16_t reg_addr, uint16_t reg_count, uint8_t frame_index, uint8_t *data);
static uint8_t cd_can_send_error_response(uint8_t func_code, uint16_t reg_addr, uint16_t reg_count, uint8_t frame_index, uint8_t error_code);
static const stc_cd_reg_map_t* cd_can_find_reg_map(uint16_t reg_addr);
static uint8_t cd_can_read_data_from_ptr(const stc_cd_reg_map_t *reg_map, uint8_t *data, uint8_t max_len);
static uint8_t cd_can_write_data_to_ptr(const stc_cd_reg_map_t *reg_map, uint8_t *data, uint8_t len);
static void cd_can_process_upgrade_message(uint16_t reg_addr, uint8_t *data);
static void cd_can_send_multi_frame_data(uint16_t reg_addr, uint16_t reg_count, uint8_t *data, uint16_t data_len, uint8_t func_code);
static uint8_t cd_can_process_multi_frame_write(uint16_t reg_addr, uint16_t reg_count, uint8_t frame_index, uint8_t *data);
static uint8_t cd_can_write_multi_register_range(uint16_t start_addr, uint16_t reg_count, uint8_t *data_buffer);
static uint8_t cd_can_process_single_frame_write(uint16_t reg_addr, uint16_t reg_count, uint8_t *data);

//----------------------------------------------------------------------------------------
// @Local Variables - 寄存器映射表，直接指向全局变量

// 统一的数据转换函数声明
uint8_t cd_transform_speed(uint8_t operation, const void *raw_data, uint8_t *data, uint8_t len);
uint8_t cd_transform_gps_speed_limit(uint8_t operation, const void *raw_data, uint8_t *data, uint8_t len);

static const stc_cd_reg_map_t g_cdRegMap[] = {
    // 通用寄存器组 (0-13) - 每个寄存器1个（uint16类型）
    {0,   CD_REG_SET_FLAGS(CD_REG_PERM_READ_ONLY, CD_DATA_TYPE_UINT16, 1), &g_stcParm.stcConfig.u16designVol, NULL}, // 软件版本号
    {1,   CD_REG_SET_FLAGS(CD_REG_PERM_READ_ONLY, CD_DATA_TYPE_UINT16, 1), &g_stcParm.stcConfig.u16designVol, NULL}, // 硬件版本号
    {2,   CD_REG_SET_FLAGS(CD_REG_PERM_READ_ONLY, CD_DATA_TYPE_UINT16, 1), NULL, NULL}, // 协议版本号
    {3,   CD_REG_SET_FLAGS(CD_REG_PERM_READ_ONLY, CD_DATA_TYPE_UINT16, 1), NULL, NULL}, // 设备标识
    {4,   CD_REG_SET_FLAGS(CD_REG_PERM_READ_ONLY, CD_DATA_TYPE_UINT16, 1), NULL, NULL}, // 设备数据协议版本号
    {5,   CD_REG_SET_FLAGS(CD_REG_PERM_WRITE_ONLY, CD_DATA_TYPE_UINT16, 1), NULL, NULL}, // 软件类型
    {6,   CD_REG_SET_FLAGS(CD_REG_PERM_WRITE_ONLY, CD_DATA_TYPE_UINT16, 1), NULL, NULL}, // 保留
    {7,   CD_REG_SET_FLAGS(CD_REG_PERM_WRITE_ONLY, CD_DATA_TYPE_UINT16, 1), NULL, NULL}, // 保留
    {8,   CD_REG_SET_FLAGS(CD_REG_PERM_WRITE_ONLY, CD_DATA_TYPE_UINT16, 1), NULL, NULL}, // 保留
    {9,   CD_REG_SET_FLAGS(CD_REG_PERM_READ_WRITE, CD_DATA_TYPE_UINT16, 1), NULL, NULL}, // 读写测试寄存器
    {10,  CD_REG_SET_FLAGS(CD_REG_PERM_READ_WRITE, CD_DATA_TYPE_UINT16, 1), &g_stcVar.binitFinishFlg, NULL}, // 上电标志位
    {12,  CD_REG_SET_FLAGS(CD_REG_PERM_READ_WRITE, CD_DATA_TYPE_UINT16, 1), NULL, NULL}, // 恢复出厂设置
    {13,  CD_REG_SET_FLAGS(CD_REG_PERM_READ_WRITE, CD_DATA_TYPE_UINT16, 1), NULL, NULL}, // 清除用户数据
    
    // 物联网模块寄存器组 (5000-5048)
    {5000, CD_REG_SET_FLAGS(CD_REG_PERM_READ_WRITE, CD_DATA_TYPE_UINT16, 1), NULL, NULL}, // 命令符
    {5001, CD_REG_SET_FLAGS(CD_REG_PERM_READ_WRITE, CD_DATA_TYPE_UINT16, 1), NULL, NULL}, // 待定
    {5002, CD_REG_SET_FLAGS(CD_REG_PERM_READ_ONLY, CD_DATA_TYPE_STRING, 10), &g_stcParm.stcConfig.ciccidSn, NULL}, // ICCID
    {5012, CD_REG_SET_FLAGS(CD_REG_PERM_READ_ONLY, CD_DATA_TYPE_STRING, 8), &g_stcParm.stcConfig.cimeiSn, NULL}, // IMEI
    {5020, CD_REG_SET_FLAGS(CD_REG_PERM_READ_ONLY, CD_DATA_TYPE_STRING, 3), &g_stcVar.u8bleMac, NULL}, // MACAddress
    {5023, CD_REG_SET_FLAGS(CD_REG_PERM_READ_ONLY, CD_DATA_TYPE_UINT16, 1), NULL, cd_transform_speed}, // 速度
    {5024, CD_REG_SET_FLAGS(CD_REG_PERM_READ_WRITE, CD_DATA_TYPE_UINT32, 2), NULL, NULL}, // 经度
    {5026, CD_REG_SET_FLAGS(CD_REG_PERM_READ_WRITE, CD_DATA_TYPE_UINT32, 2), NULL, NULL}, // 纬度
    {5028, CD_REG_SET_FLAGS(CD_REG_PERM_READ_WRITE, CD_DATA_TYPE_UINT16, 1), NULL, NULL}, // 模块模式
    {5029, CD_REG_SET_FLAGS(CD_REG_PERM_READ_WRITE, CD_DATA_TYPE_UINT16, 1), NULL, NULL}, // 心跳时间
    {5030, CD_REG_SET_FLAGS(CD_REG_PERM_READ_WRITE, CD_DATA_TYPE_UINT16, 1), NULL, NULL}, // 是否自动切换GPS
    {5031, CD_REG_SET_FLAGS(CD_REG_PERM_READ_WRITE, CD_DATA_TYPE_UINT16, 1), NULL, NULL}, // 采集GPS间隔
    {5032, CD_REG_SET_FLAGS(CD_REG_PERM_READ_WRITE, CD_DATA_TYPE_UINT16, 1), NULL, NULL}, // GPS连续采集次数
    {5033, CD_REG_SET_FLAGS(CD_REG_PERM_READ_WRITE, CD_DATA_TYPE_UINT16, 1), NULL, NULL}, // 网络状态
    {5034, CD_REG_SET_FLAGS(CD_REG_PERM_READ_WRITE, CD_DATA_TYPE_UINT16, 1), NULL, NULL}, // 注册服务器状态
    {5035, CD_REG_SET_FLAGS(CD_REG_PERM_READ_WRITE, CD_DATA_TYPE_UINT16, 1), NULL, NULL}, // GPRS信号质量
    {5036, CD_REG_SET_FLAGS(CD_REG_PERM_READ_WRITE, CD_DATA_TYPE_UINT16, 1), NULL, NULL}, // GPS信号质量
    {5037, CD_REG_SET_FLAGS(CD_REG_PERM_READ_WRITE, CD_DATA_TYPE_UINT16, 1), NULL, NULL}, // GPRS天线模式
    {5038, CD_REG_SET_FLAGS(CD_REG_PERM_READ_WRITE, CD_DATA_TYPE_UINT16, 1), NULL, NULL}, // GPS天线模式
    {5039, CD_REG_SET_FLAGS(CD_REG_PERM_READ_WRITE, CD_DATA_TYPE_UINT16, 1), NULL, cd_transform_gps_speed_limit}, // GPS上传速度限制
    {5040, CD_REG_SET_FLAGS(CD_REG_PERM_READ_WRITE, CD_DATA_TYPE_UINT16, 1), NULL, NULL}, // 模块低功耗模式
    {5041, CD_REG_SET_FLAGS(CD_REG_PERM_READ_WRITE, CD_DATA_TYPE_UINT16, 1), NULL, NULL}, // 硬件号
    {5042, CD_REG_SET_FLAGS(CD_REG_PERM_READ_WRITE, CD_DATA_TYPE_UINT16, 1), NULL, NULL}, // 软件版本号
    {5043, CD_REG_SET_FLAGS(CD_REG_PERM_READ_WRITE, CD_DATA_TYPE_UINT16, 1), NULL, NULL}, // 模块厂家代码
    {5044, CD_REG_SET_FLAGS(CD_REG_PERM_READ_WRITE, CD_DATA_TYPE_UINT16, 1), NULL, NULL}, // 待定
    {5045, CD_REG_SET_FLAGS(CD_REG_PERM_READ_WRITE, CD_DATA_TYPE_UINT16, 1), NULL, NULL}, // 待定
    {5046, CD_REG_SET_FLAGS(CD_REG_PERM_READ_WRITE, CD_DATA_TYPE_UINT16, 1), NULL, NULL}, // 待定
    {5047, CD_REG_SET_FLAGS(CD_REG_PERM_READ_WRITE, CD_DATA_TYPE_UINT16, 1), NULL, NULL}, // 待定
    {5048, CD_REG_SET_FLAGS(CD_REG_PERM_READ_WRITE, CD_DATA_TYPE_STRING, 7), NULL, NULL}, // 服务器地址（最大7个寄存器=14字节）
};

#define CD_REG_MAP_SIZE (sizeof(g_cdRegMap) / sizeof(g_cdRegMap[0]))

//========================================================================================
/*
 * @Functions:   void cd_can_init(uint8_t device_addr)
 * @Description: 初始化超电CAN协议模块
 * @Parameters:  device_addr - 设备地址
 * @Return:      NONE
 */
void cd_can_init(uint8_t device_addr)
{
    memset(&g_stcCdCan, 0, sizeof(stc_cd_can_t));
    
    g_stcCdCan.device_addr = device_addr;
    g_stcCdCan.protocol_version = (uint8_t)(CD_CAN_PROTOCOL_VERSION & 0xFF);
    
    // 初始化多帧传输管理
    g_stcCdCan.multi_frame_rx.data_buffer = g_multiFrameRxBuffer;
    g_stcCdCan.multi_frame_rx.buffer_size = CD_MAX_MULTI_FRAME_SIZE;
    
    g_stcCdCan.multi_frame_tx.data_buffer = g_multiFrameTxBuffer;
    g_stcCdCan.multi_frame_tx.buffer_size = CD_MAX_MULTI_FRAME_SIZE;
    
    // 初始化升级管理
    g_stcCdCan.upgrade.firmware_buffer = g_firmwareBuffer;
    g_stcCdCan.upgrade.buffer_size = CD_MAX_FIRMWARE_SIZE;
    g_stcCdCan.upgrade.upgrade_state = CD_UPGRADE_STATE_IDLE;
    
    printf("Chaodian CAN Protocol Module Initialized, Device Addr: 0x%02X\r\n", device_addr);
}


/*
 * @Functions:   void cd_can_process_message(uint32_t can_id, uint8_t *data, uint8_t length)
 * @Description: 处理接收到的CAN消息
 * @Parameters:  can_id - CAN ID
 *               data - 数据指针
 *               length - 数据长度
 * @Return:      NONE
 */
void cd_can_process_message(uint32_t can_id, uint8_t *data, uint8_t length)
{
    uint8_t func_code, dst_addr, src_addr;
    uint16_t reg_addr;
    stc_cd_can_msg_t msg;
    
    // 更新统计信息
    g_stcCdCan.stats.rx_count++;
    
    // 解析CAN ID
    if (!cd_can_parse_id(can_id, &func_code, &reg_addr, &dst_addr, &src_addr))
    {
        g_stcCdCan.stats.error_count++;
        return;
    }
    
    // 检查是否是发给本设备的
    if (!cd_can_is_for_me(can_id, g_stcCdCan.device_addr))
    {
        return; // 忽略非发给本设备的消息
    }
    
    // 检查数据长度
    if (length < 4)
    {
        g_stcCdCan.stats.error_count++;
        return;
    }
    
    // 解析消息内容
    msg.func_code = data[0];
    msg.reg_count = (data[1] << 8) | data[2];
    msg.frame_index = data[3];
    memcpy(msg.data, &data[4], (length > 4) ? (length - 4) : 0);
    
    // 根据功能码处理消息
    switch (msg.func_code)
    {
        case CD_FUNC_READ_REG:
            // 处理读寄存器请求
            cd_can_process_read_request(reg_addr, msg.reg_count, msg.frame_index, msg.data);
            break;
            
        case CD_FUNC_WRITE_REG:
            // 处理写寄存器请求
            cd_can_process_write_request(reg_addr, msg.reg_count, msg.frame_index, msg.data);
            break;
            
        case CD_FUNC_UPGRADE:
            // 处理升级相关消息
            cd_can_process_upgrade_message(reg_addr, msg.data);
            break;
            
        default:
            // 发送非法功能错误
            cd_can_send_error_response(msg.func_code, reg_addr, msg.reg_count, msg.frame_index, CD_ERROR_ILLEGAL_FUNC);
            break;
    }
}

/*
 * @Functions:   static void cd_can_process_read_request(uint16_t reg_addr, uint16_t reg_count, uint8_t frame_index, uint8_t *data)
 * @Description: 处理读寄存器请求
 * @Parameters:  reg_addr - 寄存器地址
 *               reg_count - 寄存器数量
 *               frame_index - 帧索引
 *               data - 数据
 * @Return:      NONE
 */
static void cd_can_process_read_request(uint16_t reg_addr, uint16_t reg_count, uint8_t frame_index, uint8_t *data)
{
    uint8_t response_data[CD_MAX_MULTI_FRAME_SIZE];
    uint8_t error_code = CD_ERROR_SUCCESS;
    uint16_t data_len = 0;
    
    // 检查寄存器访问权限
    if (!cd_can_is_reg_readable(reg_addr))
    {
        error_code = CD_ERROR_ILLEGAL_ADDR;
    }
    else if (reg_count == 0 || reg_count > CD_MAX_REG_COUNT)
    {
        error_code = CD_ERROR_ILLEGAL_VALUE;
    }
    else
    {
        // 读取所有寄存器数据
        uint16_t current_addr = reg_addr;
        uint16_t remaining_regs = reg_count;
        
        while (remaining_regs > 0 && data_len < CD_MAX_MULTI_FRAME_SIZE)
        {
            const stc_cd_reg_map_t *reg_map = cd_can_find_reg_map(current_addr);
            if (reg_map == NULL)
            {
                // 寄存器不存在，填充0xFF
                uint8_t fill_bytes = (remaining_regs > 1) ? 2 : (remaining_regs * 2);
                memset(&response_data[data_len], 0xFF, fill_bytes);
                data_len += fill_bytes;
                remaining_regs -= 1;
                current_addr += 1;
            }
            else
            {
                // 获取寄存器实际长度
                uint8_t reg_size = CD_REG_GET_SIZE(reg_map->flags);
                uint8_t byte_count = reg_size * 2;  // 寄存器数量 * 2 = 字节数
                
                // 检查缓冲区空间
                if (data_len + byte_count > CD_MAX_MULTI_FRAME_SIZE)
                {
                    break; // 缓冲区空间不足
                }
                
                // 读取寄存器数据
                if (cd_can_read_register(current_addr, &response_data[data_len], byte_count) > 0)
                {
                    data_len += byte_count;
                }
                else
                {
                    // 读取失败，填充0xFF
                    memset(&response_data[data_len], 0xFF, byte_count);
                    data_len += byte_count;
                }
                
                // 更新地址和剩余寄存器数
                remaining_regs -= reg_size;
                current_addr += reg_size;
            }
        }
        
        if (data_len == 0)
        {
            error_code = CD_ERROR_SLAVE_FAILURE;
        }
    }
    
    // 发送响应
    if (error_code == CD_ERROR_SUCCESS)
    {
        // 检查是否需要多帧响应
        if (data_len > 4)
        {
            // 发送多帧响应
            cd_can_send_multi_frame_data(reg_addr, reg_count, response_data, data_len, CD_FUNC_READ_REG);
        }
        else
        {
            // 发送单帧响应
            cd_can_send_read_response(reg_addr, reg_count, frame_index, response_data, CD_ERROR_SUCCESS);
        }
    }
    else
    {
        cd_can_send_error_response(CD_FUNC_READ_REG_ERROR, reg_addr, reg_count, frame_index, error_code);
    }
}

/*
 * @Functions:   static void cd_can_process_write_request(uint16_t reg_addr, uint16_t reg_count, uint8_t frame_index, uint8_t *data)
 * @Description: 处理写寄存器请求（支持多帧写入）
 * @Parameters:  reg_addr - 寄存器地址
 *               reg_count - 寄存器数量
 *               frame_index - 帧索引
 *               data - 数据
 * @Return:      NONE
 */
static void cd_can_process_write_request(uint16_t reg_addr, uint16_t reg_count, uint8_t frame_index, uint8_t *data)
{
    uint8_t error_code = CD_ERROR_SUCCESS;
    
    // 检查寄存器访问权限
    if (!cd_can_is_reg_writable(reg_addr))
    {
        error_code = CD_ERROR_ILLEGAL_ADDR;
    }
    else if (reg_count == 0 || reg_count > CD_MAX_REG_COUNT)
    {
        error_code = CD_ERROR_ILLEGAL_VALUE;
    }
    else
    {
        // 检查是否需要多帧处理
        uint8_t frames_needed = (reg_count + 1) / 2; // 每帧2个寄存器，向上取整
        
        if (frames_needed > 1)
        {
            // 多帧写入处理
            error_code = cd_can_process_multi_frame_write(reg_addr, reg_count, frame_index, data);
        }
        else
        {
            // 单帧写入处理
            error_code = cd_can_process_single_frame_write(reg_addr, reg_count, data);
        }
    }
    
    // 发送响应
    if (error_code == CD_ERROR_SUCCESS)
    {
        cd_can_send_write_response(reg_addr, reg_count, frame_index, CD_ERROR_SUCCESS);
    }
    else
    {
        cd_can_send_error_response(CD_FUNC_WRITE_REG_ERROR, reg_addr, reg_count, frame_index, error_code);
    }
}

/*
 * @Functions:   static uint8_t cd_can_send_read_response(uint16_t reg_addr, uint16_t reg_count, uint8_t frame_index, uint8_t *data, uint8_t error_code)
 * @Description: 发送读寄存器响应
 * @Parameters:  reg_addr - 寄存器地址
 *               reg_count - 寄存器数量
 *               frame_index - 帧索引
 *               data - 数据
 *               error_code - 错误码
 * @Return:      0-失败, 1-成功
 */
static uint8_t cd_can_send_read_response(uint16_t reg_addr, uint16_t reg_count, uint8_t frame_index, uint8_t *data, uint8_t error_code)
{
    uint32_t can_id;
    uint8_t u8CanBuf[8];
    
    // 构建CAN ID
    can_id = cd_can_build_id(CD_FUNC_READ_REG, reg_addr, CD_DEVICE_ADDR_HOST, g_stcCdCan.device_addr);
    
    // 构建数据
    u8CanBuf[0] = CD_FUNC_READ_REG;
    u8CanBuf[1] = (reg_count >> 8) & 0xFF;
    u8CanBuf[2] = reg_count & 0xFF;
    u8CanBuf[3] = frame_index;
    
    if (error_code == CD_ERROR_SUCCESS && data != NULL)
    {
        memcpy(&u8CanBuf[4], data, 4);
    }
    else
    {
        memset(&u8CanBuf[4], CD_DATA_FILL, 4);
    }
    
    // 将数据放入CAN发送队列
    if (g_stccan.vu8canTxMQPushLen < CAN_MAX_TX_SIZE)/*保护，防止溢出*/
    {
        /* Init Transmit frame*/
        g_stccan.canTxMessage[g_stccan.vu8canTxMQPushLen].ExtId   = can_id; 
        g_stccan.canTxMessage[g_stccan.vu8canTxMQPushLen].IDE     = CAN_ID_EXT;  
        g_stccan.canTxMessage[g_stccan.vu8canTxMQPushLen].RTR     = CAN_RTRQ_DATA;   
        g_stccan.canTxMessage[g_stccan.vu8canTxMQPushLen].DLC     = CAN_TXDLC_8;  
        memcpy(g_stccan.canTxMessage[g_stccan.vu8canTxMQPushLen].Data, &u8CanBuf[0], 8);
        g_stccan.vu8canTxMQPushLen++;
    }
    if (g_stccan.vu8canTxMQPushLen >= CAN_MAX_TX_SIZE)
    {
        g_stccan.vu8canTxMQPushLen = 0;
    }
    
    g_stcCdCan.stats.tx_count++;
    return 1;
}

/*
 * @Functions:   static uint8_t cd_can_send_write_response(uint16_t reg_addr, uint16_t reg_count, uint8_t frame_index, uint8_t error_code)
 * @Description: 发送写寄存器响应
 * @Parameters:  reg_addr - 寄存器地址
 *               reg_count - 寄存器数量
 *               frame_index - 帧索引
 *               error_code - 错误码
 * @Return:      0-失败, 1-成功
 */
static uint8_t cd_can_send_write_response(uint16_t reg_addr, uint16_t reg_count, uint8_t frame_index, uint8_t error_code)
{
    uint32_t can_id;
    uint8_t u8CanBuf[8];
    
    // 构建CAN ID
    can_id = cd_can_build_id(CD_FUNC_WRITE_REG, reg_addr, CD_DEVICE_ADDR_HOST, g_stcCdCan.device_addr);
    
    // 构建数据
    u8CanBuf[0] = CD_FUNC_WRITE_REG;
    u8CanBuf[1] = (reg_count >> 8) & 0xFF;
    u8CanBuf[2] = reg_count & 0xFF;
    u8CanBuf[3] = frame_index;
    memset(&u8CanBuf[4], CD_DATA_FILL, 4);
    
    // 将数据放入CAN发送队列
    if (g_stccan.vu8canTxMQPushLen < CAN_MAX_TX_SIZE)/*保护，防止溢出*/
    {
        /* Init Transmit frame*/
        g_stccan.canTxMessage[g_stccan.vu8canTxMQPushLen].ExtId   = can_id; 
        g_stccan.canTxMessage[g_stccan.vu8canTxMQPushLen].IDE     = CAN_ID_EXT;  
        g_stccan.canTxMessage[g_stccan.vu8canTxMQPushLen].RTR     = CAN_RTRQ_DATA;   
        g_stccan.canTxMessage[g_stccan.vu8canTxMQPushLen].DLC     = CAN_TXDLC_8;  
        memcpy(g_stccan.canTxMessage[g_stccan.vu8canTxMQPushLen].Data, &u8CanBuf[0], 8);
        g_stccan.vu8canTxMQPushLen++;
    }
    if (g_stccan.vu8canTxMQPushLen >= CAN_MAX_TX_SIZE)
    {
        g_stccan.vu8canTxMQPushLen = 0;
    }
    
    g_stcCdCan.stats.tx_count++;
    return 1;
}

/*
 * @Functions:   static uint8_t cd_can_send_event_report(uint16_t reg_addr, uint8_t *data)
 * @Description: 发送事件上报
 * @Parameters:  reg_addr - 寄存器地址
 *               data - 数据
 * @Return:      0-失败, 1-成功
 */
static uint8_t cd_can_send_event_report(uint16_t reg_addr, uint8_t *data)
{
    uint32_t can_id;
    uint8_t u8CanBuf[8];
    
    // 构建CAN ID
    can_id = cd_can_build_id(CD_FUNC_EVENT_REPORT, reg_addr, CD_DEVICE_ADDR_HOST, g_stcCdCan.device_addr);
    
    // 构建数据
    u8CanBuf[0] = CD_FUNC_EVENT_REPORT;
    u8CanBuf[1] = 0x00; // 寄存器数量高字节
    u8CanBuf[2] = 0x01; // 寄存器数量低字节
    u8CanBuf[3] = 0x00; // 帧索引
    
    if (data != NULL)
    {
        memcpy(&u8CanBuf[4], data, 4);
    }
    else
    {
        memset(&u8CanBuf[4], CD_DATA_FILL, 4);
    }
    
    // 将数据放入CAN发送队列
    if (g_stccan.vu8canTxMQPushLen < CAN_MAX_TX_SIZE)/*保护，防止溢出*/
    {
        /* Init Transmit frame*/
        g_stccan.canTxMessage[g_stccan.vu8canTxMQPushLen].ExtId   = can_id; 
        g_stccan.canTxMessage[g_stccan.vu8canTxMQPushLen].IDE     = CAN_ID_EXT;  
        g_stccan.canTxMessage[g_stccan.vu8canTxMQPushLen].RTR     = CAN_RTRQ_DATA;   
        g_stccan.canTxMessage[g_stccan.vu8canTxMQPushLen].DLC     = CAN_TXDLC_8;  
        memcpy(g_stccan.canTxMessage[g_stccan.vu8canTxMQPushLen].Data, &u8CanBuf[0], 8);
        g_stccan.vu8canTxMQPushLen++;
    }
    if (g_stccan.vu8canTxMQPushLen >= CAN_MAX_TX_SIZE)
    {
        g_stccan.vu8canTxMQPushLen = 0;
    }
    
    g_stcCdCan.stats.tx_count++;
    return 1;
}

/*
 * @Functions:   static uint32_t cd_can_build_id(uint8_t func_code, uint16_t reg_addr, uint8_t dst_addr, uint8_t src_addr)
 * @Description: 构建CAN ID
 * @Parameters:  func_code - 功能码
 *               reg_addr - 寄存器地址
 *               dst_addr - 目标设备地址
 *               src_addr - 源设备地址
 * @Return:      CAN ID
 */
static uint32_t cd_can_build_id(uint8_t func_code, uint16_t reg_addr, uint8_t dst_addr, uint8_t src_addr)
{
    return CD_BUILD_CAN_ID(func_code, reg_addr, dst_addr, src_addr);
}

/*
 * @Functions:   static uint8_t cd_can_parse_id(uint32_t can_id, uint8_t *func_code, uint16_t *reg_addr, uint8_t *dst_addr, uint8_t *src_addr)
 * @Description: 解析CAN ID
 * @Parameters:  can_id - CAN ID
 *               func_code - 功能码指针
 *               reg_addr - 寄存器地址指针
 *               dst_addr - 目标设备地址指针
 *               src_addr - 源设备地址指针
 * @Return:      0-失败, 1-成功
 */
static uint8_t cd_can_parse_id(uint32_t can_id, uint8_t *func_code, uint16_t *reg_addr, uint8_t *dst_addr, uint8_t *src_addr)
{
    if (func_code == NULL || reg_addr == NULL || dst_addr == NULL || src_addr == NULL)
    {
        return 0;
    }
    
    *func_code = (can_id & CD_CAN_ID_FUNC_MASK) >> CD_CAN_ID_FUNC_SHIFT;
    *reg_addr = (can_id & CD_CAN_ID_REG_MASK) >> CD_CAN_ID_REG_SHIFT;
    *dst_addr = (can_id & CD_CAN_ID_DST_MASK) >> CD_CAN_ID_DST_SHIFT;
    *src_addr = (can_id & CD_CAN_ID_SRC_MASK) >> CD_CAN_ID_SRC_SHIFT;
    
    return 1;
}

/*
 * @Functions:   static uint8_t cd_can_is_for_me(uint32_t can_id, uint8_t my_addr)
 * @Description: 检查CAN消息是否是发给本设备的
 * @Parameters:  can_id - CAN ID
 *               my_addr - 本设备地址
 * @Return:      0-不是, 1-是
 */
static uint8_t cd_can_is_for_me(uint32_t can_id, uint8_t my_addr)
{
    uint8_t dst_addr;
    cd_can_parse_id(can_id, NULL, NULL, &dst_addr, NULL);
    return (dst_addr == my_addr);
}

/*
 * @Functions:   static uint8_t cd_can_read_register(uint16_t reg_addr, uint8_t *data, uint8_t max_len)
 * @Description: 读取寄存器数据
 * @Parameters:  reg_addr - 寄存器地址
 *               data - 数据缓冲区
 *               max_len - 最大长度
 * @Return:      实际读取的数据长度
 */
static uint8_t cd_can_read_register(uint16_t reg_addr, uint8_t *data, uint8_t max_len)
{
    const stc_cd_reg_map_t *reg_map;
    
    if (data == NULL || max_len == 0)
    {
        return 0;
    }
    
    // 查找寄存器映射
    reg_map = cd_can_find_reg_map(reg_addr);
    if (reg_map == NULL)
    {
        return 0;
    }
    
    return cd_can_read_data_from_ptr(reg_map, data, max_len);
}

/*
 * @Functions:   static uint8_t cd_can_write_register(uint16_t reg_addr, uint8_t *data, uint8_t len)
 * @Description: 写入寄存器数据
 * @Parameters:  reg_addr - 寄存器地址
 *               data - 数据
 *               len - 数据长度
 * @Return:      0-失败, 1-成功
 */
static uint8_t cd_can_write_register(uint16_t reg_addr, uint8_t *data, uint8_t len)
{
    const stc_cd_reg_map_t *reg_map;
    
    if (data == NULL || len == 0)
    {
        return 0;
    }
    
    // 查找寄存器映射
    reg_map = cd_can_find_reg_map(reg_addr);
    if (reg_map == NULL)
    {
        return 0;
    }
    
    return cd_can_write_data_to_ptr(reg_map, data, len);
}

/*
 * @Functions:   static uint8_t cd_can_is_reg_readable(uint16_t reg_addr)
 * @Description: 检查寄存器是否可读
 * @Parameters:  reg_addr - 寄存器地址
 * @Return:      0-不可读, 1-可读
 */
static uint8_t cd_can_is_reg_readable(uint16_t reg_addr)
{
    const stc_cd_reg_map_t *reg_map;
    
    reg_map = cd_can_find_reg_map(reg_addr);
    if (reg_map == NULL)
    {
        return 0;
    }
    
    return (CD_REG_GET_PERM(reg_map->flags) & CD_REG_PERM_READ_ONLY) != 0;
}

/*
 * @Functions:   static uint8_t cd_can_is_reg_writable(uint16_t reg_addr)
 * @Description: 检查寄存器是否可写
 * @Parameters:  reg_addr - 寄存器地址
 * @Return:      0-不可写, 1-可写
 */
static uint8_t cd_can_is_reg_writable(uint16_t reg_addr)
{
    const stc_cd_reg_map_t *reg_map;
    
    reg_map = cd_can_find_reg_map(reg_addr);
    if (reg_map == NULL)
    {
        return 0;
    }
    
    return (CD_REG_GET_PERM(reg_map->flags) & CD_REG_PERM_WRITE_ONLY) != 0;
}

/*
 * @Functions:   static void cd_can_get_stats(uint32_t *rx_count, uint32_t *tx_count, uint32_t *error_count, uint32_t *timeout_count)
 * @Description: 获取统计信息
 * @Parameters:  rx_count - 接收计数指针
 *               tx_count - 发送计数指针
 *               error_count - 错误计数指针
 *               timeout_count - 超时计数指针
 * @Return:      NONE
 */
static void cd_can_get_stats(uint32_t *rx_count, uint32_t *tx_count, uint32_t *error_count, uint32_t *timeout_count)
{
    if (rx_count) *rx_count = g_stcCdCan.stats.rx_count;
    if (tx_count) *tx_count = g_stcCdCan.stats.tx_count;
    if (error_count) *error_count = g_stcCdCan.stats.error_count;
    if (timeout_count) *timeout_count = g_stcCdCan.stats.timeout_count;
}

/*
 * @Functions:   static void cd_can_reset_stats(void)
 * @Description: 重置统计信息
 * @Parameters:  NONE
 * @Return:      NONE
 */
static void cd_can_reset_stats(void)
{
    memset(&g_stcCdCan.stats, 0, sizeof(g_stcCdCan.stats));
}

//----------------------------------------------------------------------------------------
// @Local Functions

/*
 * @Functions:   static uint8_t cd_can_process_single_frame_write(uint16_t reg_addr, uint16_t reg_count, uint8_t *data)
 * @Description: 处理单帧写入请求（最多2个寄存器，4字节数据）
 * @Parameters:  reg_addr - 寄存器地址
 *               reg_count - 寄存器数量
 *               data - 数据（4字节）
 * @Return:      错误码
 */
static uint8_t cd_can_process_single_frame_write(uint16_t reg_addr, uint16_t reg_count, uint8_t *data)
{
    uint16_t current_addr = reg_addr;
    uint16_t data_offset = 0;
    uint16_t remaining_regs = reg_count;
    
    printf("Chaodian CAN: Processing single frame write, Reg[%d], Count[%d]\r\n", reg_addr, reg_count);
    
    // 单帧最多包含2个寄存器（4字节数据）
    if (reg_count > 2)
    {
        printf("Chaodian CAN: Single frame register count exceeds limit: %d\r\n", reg_count);
        return CD_ERROR_ILLEGAL_VALUE;
    }
    
    while (remaining_regs > 0)
    {
        const stc_cd_reg_map_t *reg_map = cd_can_find_reg_map(current_addr);
        
        uint8_t item_reg_count = CD_REG_GET_SIZE(reg_map->flags);
        
        if (item_reg_count == 2 && remaining_regs >= 2)
        {
            // 当前数据项占2个寄存器，且还有2个寄存器要处理，作为整体写入
            printf("Chaodian CAN: Writing complete 2-register data item at Reg[%d]\r\n", current_addr);
            
            if (cd_can_write_register(current_addr, &data[data_offset], 4) == 0)
            {
                printf("Chaodian CAN: Failed to write complete data item at Reg[%d]\r\n", current_addr);
                return CD_ERROR_SLAVE_FAILURE;
            }
            
            printf("Chaodian CAN: Successfully wrote complete data item at Reg[%d]\r\n", current_addr);
            printf("Chaodian CAN: Data: %02X %02X %02X %02X\r\n", 
                    data[data_offset], data[data_offset + 1], data[data_offset + 2], data[data_offset + 3]);
            
            // 处理完成，直接结束
            return CD_ERROR_SUCCESS;
        }
        else
        {
            // 当前数据项只占1个寄存器，或剩余寄存器不足2个，单独写入
            printf("Chaodian CAN: Writing single register at Reg[%d]\r\n", current_addr);
            
            uint8_t reg_data[2] = {data[data_offset], data[data_offset + 1]};
            
            if (cd_can_write_register(current_addr, reg_data, 2) == 0)
            {
                printf("Chaodian CAN: Failed to write register[%d]\r\n", current_addr);
                return CD_ERROR_SLAVE_FAILURE;
            }
            
            printf("Chaodian CAN: Write Reg[%d] = 0x%04X\r\n", 
                    current_addr, (reg_data[0] << 8) | reg_data[1]);
            
            // 移动到下一个地址
            current_addr += item_reg_count;
            data_offset += 2;
            remaining_regs -= 1;
        }
    }
    
    printf("Chaodian CAN: Single frame write completed successfully\r\n");
    return CD_ERROR_SUCCESS;
}

/*
 * @Functions:   static uint8_t cd_can_write_multi_register_range(uint16_t start_addr, uint16_t reg_count, uint8_t *data_buffer)
 * @Description: 写入多寄存器范围，支持跨多个寄存器映射项
 * @Parameters:  start_addr - 起始寄存器地址
 *               reg_count - 寄存器数量
 *               data_buffer - 数据缓冲区
 * @Return:      0-失败, 1-成功
 */
static uint8_t cd_can_write_multi_register_range(uint16_t start_addr, uint16_t reg_count, uint8_t *data_buffer)
{
    uint16_t current_addr = start_addr;
    uint16_t remaining_regs = reg_count;
    uint16_t data_offset = 0;
    uint8_t write_success = 1;
    
    printf("Chaodian CAN: Writing register range [%d-%d], %d registers\r\n", 
           start_addr, start_addr + reg_count - 1, reg_count);
    
    while (remaining_regs > 0 && write_success)
    {
        // 查找当前地址的寄存器映射
        const stc_cd_reg_map_t *reg_map = cd_can_find_reg_map(current_addr);
        
        if (reg_map != NULL)
        {
            // 获取当前数据项的大小
            uint8_t item_reg_count = CD_REG_GET_SIZE(reg_map->flags);
            uint8_t item_bytes = item_reg_count * 2;
            
            // 计算当前数据项实际需要写入的寄存器数量
            uint8_t write_reg_count = (remaining_regs < item_reg_count) ? remaining_regs : item_reg_count;
            uint8_t write_bytes = write_reg_count * 2;
            
            printf("Chaodian CAN: Processing Reg[%d], ItemSize[%d], WriteSize[%d]\r\n", 
                   current_addr, item_reg_count, write_reg_count);
            
            // 检查是否跨越数据项边界
            if (write_reg_count == item_reg_count)
            {
                // 完整写入一个数据项
                printf("Chaodian CAN: Writing complete data item at Reg[%d], %d bytes\r\n", 
                       current_addr, write_bytes);
                
                if (cd_can_write_register(current_addr, &data_buffer[data_offset], write_bytes) == 0)
                {
                    printf("Chaodian CAN: Failed to write complete data item at Reg[%d]\r\n", current_addr);
                    write_success = 0;
                }
                else
                {
                    printf("Chaodian CAN: Successfully wrote complete data item at Reg[%d]\r\n", current_addr);
                }
            }
            else
            {
                // 部分写入数据项，按单个寄存器写入
                printf("Chaodian CAN: Writing partial data item at Reg[%d], %d registers\r\n", 
                       current_addr, write_reg_count);
                
                for (uint8_t i = 0; i < write_reg_count && write_success; i++)
                {
                    uint16_t reg_addr = current_addr + i;
                    uint8_t reg_data[2];
                    
                    reg_data[0] = data_buffer[data_offset + i * 2];
                    reg_data[1] = data_buffer[data_offset + i * 2 + 1];
                    
                    if (cd_can_write_register(reg_addr, reg_data, 2) == 0)
                    {
                        printf("Chaodian CAN: Failed to write register[%d]\r\n", reg_addr);
                        write_success = 0;
                    }
                    else
                    {
                        printf("Chaodian CAN: Write Reg[%d] = 0x%04X\r\n", 
                               reg_addr, (reg_data[0] << 8) | reg_data[1]);
                    }
                }
            }
            
            // 更新地址和偏移
            current_addr += item_reg_count;
            data_offset += write_bytes;
            remaining_regs -= write_reg_count;
        }
        else
        {
            // 没有寄存器映射，按单个寄存器写入
            printf("Chaodian CAN: No mapping for Reg[%d], writing individually\r\n", current_addr);
            
            uint8_t reg_data[2];
            reg_data[0] = data_buffer[data_offset];
            reg_data[1] = data_buffer[data_offset + 1];
            
            if (cd_can_write_register(current_addr, reg_data, 2) == 0)
            {
                printf("Chaodian CAN: Failed to write register[%d]\r\n", current_addr);
                write_success = 0;
            }
            else
            {
                printf("Chaodian CAN: Write Reg[%d] = 0x%04X\r\n", 
                       current_addr, (reg_data[0] << 8) | reg_data[1]);
            }
            
            // 更新地址和偏移
            current_addr += 1;
            data_offset += 2;
            remaining_regs -= 1;
        }
    }
    
    if (write_success)
    {
        printf("Chaodian CAN: Multi-register range write completed successfully\r\n");
    }
    else
    {
        printf("Chaodian CAN: Multi-register range write failed\r\n");
    }
    
    return write_success;
}

/*
 * @Functions:   static uint8_t cd_can_process_multi_frame_write(uint16_t reg_addr, uint16_t reg_count, uint8_t frame_index, uint8_t *data)
 * @Description: 处理多帧写入请求
 * @Parameters:  reg_addr - 寄存器地址
 *               reg_count - 寄存器数量
 *               frame_index - 帧索引
 *               data - 数据
 * @Return:      错误码
 */
static uint8_t cd_can_process_multi_frame_write(uint16_t reg_addr, uint16_t reg_count, uint8_t frame_index, uint8_t *data)
{
    stc_cd_multi_frame_t *rx_frame = &g_stcCdCan.multi_frame_rx;
    uint32_t current_tick = drv_systick_getTick();
    
    // 如果是第一帧，初始化多帧接收
    if (frame_index == 0)
    {
        // 检查是否有正在进行的多帧传输
        if (rx_frame->active)
        {
            printf("Chaodian CAN: Multi-frame write already in progress\r\n");
            return CD_ERROR_SLAVE_FAILURE;
        }
        
        // 初始化多帧接收
        rx_frame->reg_addr = reg_addr;
        rx_frame->reg_count = reg_count;
        rx_frame->total_frames = (reg_count + 1) / 2; // 每帧2个寄存器
        rx_frame->current_frame_idx = 0;
        rx_frame->active = 1;
        rx_frame->last_update_tick = current_tick;
        rx_frame->func_code = CD_FUNC_WRITE_REG;
        
        printf("Chaodian CAN: Start multi-frame write, Reg[%d], Count[%d], Frames[%d]\r\n", 
               reg_addr, reg_count, rx_frame->total_frames);
    }
    
    // 检查帧索引是否匹配
    if (frame_index != rx_frame->current_frame_idx)
    {
        printf("Chaodian CAN: Frame index mismatch, Expected[%d], Received[%d]\r\n", 
               rx_frame->current_frame_idx, frame_index);
        return CD_ERROR_ILLEGAL_VALUE;
    }
    
    // 检查是否超时
    if (current_tick - rx_frame->last_update_tick > CD_CAN_MULTI_FRAME_TIMEOUT_MS)
    {
        printf("Chaodian CAN: Multi-frame write timeout\r\n");
        rx_frame->active = 0;
        return CD_ERROR_SLAVE_FAILURE;
    }
    
    // 存储帧数据
    uint16_t data_offset = frame_index * 4; // 每帧4字节数据
    if (data_offset + 4 <= rx_frame->buffer_size)
    {
        memcpy(&rx_frame->data_buffer[data_offset], data, 4);
        rx_frame->current_frame_idx++;
        rx_frame->last_update_tick = current_tick;
        
        printf("Chaodian CAN: Received frame[%d], Data: %02X %02X %02X %02X\r\n", 
               frame_index, data[0], data[1], data[2], data[3]);
    }
    else
    {
        printf("Chaodian CAN: Multi-frame buffer overflow\r\n");
        rx_frame->active = 0;
        return CD_ERROR_SLAVE_FAILURE;
    }
    
    // 检查是否接收完所有帧
    if (rx_frame->current_frame_idx >= rx_frame->total_frames)
    {
        // 所有帧接收完成，开始写入寄存器
        printf("Chaodian CAN: All frames received, writing to registers\r\n");
        
        uint8_t write_success = cd_can_write_multi_register_range(reg_addr, reg_count, rx_frame->data_buffer);
        
        // 清除多帧接收状态
        rx_frame->active = 0;
        
        if (!write_success)
        {
            return CD_ERROR_SLAVE_FAILURE;
        }
        
        printf("Chaodian CAN: Multi-frame write completed successfully\r\n");
    }
    
    return CD_ERROR_SUCCESS;
}


/*
 * @Functions:   static uint8_t cd_can_send_error_response(uint8_t func_code, uint16_t reg_addr, uint16_t reg_count, uint8_t frame_index, uint8_t error_code)
 * @Description: 发送错误响应
 * @Parameters:  func_code - 功能码
 *               reg_addr - 寄存器地址
 *               reg_count - 寄存器数量
 *               frame_index - 帧索引
 *               error_code - 错误码
 * @Return:      0-失败, 1-成功
 */
static uint8_t cd_can_send_error_response(uint8_t func_code, uint16_t reg_addr, uint16_t reg_count, uint8_t frame_index, uint8_t error_code)
{
    uint32_t can_id;
    uint8_t u8CanBuf[8];
    
    // 构建CAN ID
    can_id = cd_can_build_id(func_code, reg_addr, CD_DEVICE_ADDR_HOST, g_stcCdCan.device_addr);
    
    // 构建数据
    u8CanBuf[0] = func_code;
    u8CanBuf[1] = (reg_count >> 8) & 0xFF;
    u8CanBuf[2] = reg_count & 0xFF;
    u8CanBuf[3] = frame_index;
    u8CanBuf[4] = error_code;
    memset(&u8CanBuf[5], CD_DATA_FILL, 3);
    
    // 将数据放入CAN发送队列
    if (g_stccan.vu8canTxMQPushLen < CAN_MAX_TX_SIZE)/*保护，防止溢出*/
    {
        /* Init Transmit frame*/
        g_stccan.canTxMessage[g_stccan.vu8canTxMQPushLen].ExtId   = can_id; 
        g_stccan.canTxMessage[g_stccan.vu8canTxMQPushLen].IDE     = CAN_ID_EXT;  
        g_stccan.canTxMessage[g_stccan.vu8canTxMQPushLen].RTR     = CAN_RTRQ_DATA;   
        g_stccan.canTxMessage[g_stccan.vu8canTxMQPushLen].DLC     = CAN_TXDLC_8;  
        memcpy(g_stccan.canTxMessage[g_stccan.vu8canTxMQPushLen].Data, &u8CanBuf[0], 8);
        g_stccan.vu8canTxMQPushLen++;
    }
    if (g_stccan.vu8canTxMQPushLen >= CAN_MAX_TX_SIZE)
    {
        g_stccan.vu8canTxMQPushLen = 0;
    }
    
    g_stcCdCan.stats.tx_count++;
    return 1;
}

/*
 * @Functions:   static const stc_cd_reg_map_t* cd_can_find_reg_map(uint16_t reg_addr)
 * @Description: 查找寄存器映射
 * @Parameters:  reg_addr - 寄存器地址
 * @Return:      寄存器映射指针，NULL表示未找到
 */
static const stc_cd_reg_map_t* cd_can_find_reg_map(uint16_t reg_addr)
{
    uint16_t i;
    
    for (i = 0; i < CD_REG_MAP_SIZE; i++)
    {
        if (g_cdRegMap[i].reg_addr == reg_addr)
        {
            return &g_cdRegMap[i];
        }
    }
    
    return NULL;
}

/*
 * @Functions:   static uint8_t cd_can_read_data_from_ptr(const stc_cd_reg_map_t *reg_map, uint8_t *data, uint8_t max_len)
 * @Description: 从data_ptr读取数据
 * @Parameters:  reg_map - 寄存器映射指针
 *               data - 数据缓冲区
 *               max_len - 最大长度
 * @Return:      实际读取的数据长度
 */
static uint8_t cd_can_read_data_from_ptr(const stc_cd_reg_map_t *reg_map, uint8_t *data, uint8_t max_len)
{
    uint8_t data_len = 0;
    
    if (reg_map == NULL || data == NULL || max_len == 0)
    {
        return 0;
    }
    
    // 如果有data_ptr，从全局变量读取
    if (reg_map->data_ptr != NULL)
    {
        // 如果有转换函数，使用统一转换函数
        if (reg_map->transform_func != NULL)
        {
            data_len = reg_map->transform_func(CD_TRANSFORM_READ, reg_map->data_ptr, data, max_len);
        }
        else
        {
            // 没有转换函数，直接读取原始数据
            switch (CD_REG_GET_TYPE(reg_map->flags))
            {
                case CD_DATA_TYPE_UINT8:
                    if (max_len >= 1)
                    {
                        data[0] = *(uint8_t*)reg_map->data_ptr;
                        data_len = 1;
                    }
                    break;
                    
                case CD_DATA_TYPE_UINT16:
                    if (max_len >= 2)
                    {
                        uint16_t value = *(uint16_t*)reg_map->data_ptr;
                        data[0] = (value >> 8) & 0xFF;
                        data[1] = value & 0xFF;
                        data_len = 2;
                    }
                    break;
                    
                case CD_DATA_TYPE_UINT32:
                    if (max_len >= 4)
                    {
                        uint32_t value = *(uint32_t*)reg_map->data_ptr;
                        data[0] = (value >> 24) & 0xFF;
                        data[1] = (value >> 16) & 0xFF;
                        data[2] = (value >> 8) & 0xFF;
                        data[3] = value & 0xFF;
                        data_len = 4;
                    }
                    break;
                    
                case CD_DATA_TYPE_STRING:
                    {
                        uint8_t reg_count = CD_REG_GET_SIZE(reg_map->flags);
                        uint8_t byte_count = reg_count * 2;  // 寄存器数量 * 2 = 字节数
                        uint8_t copy_len = (byte_count < max_len) ? byte_count : max_len;
                        memcpy(data, reg_map->data_ptr, copy_len);
                        data_len = copy_len;
                    }
                    break;
                    
                default:
                    break;
            }
        }
    }
    else
    {
        // 没有data_ptr，返回0xFF填充值（符合协议要求）
        if (max_len >= 2)
        {
            data[0] = 0xFF;
            data[1] = 0xFF;
            data_len = 2;
        }
    }
    
    return data_len;
}

/*
 * @Functions:   static uint8_t cd_can_write_data_to_ptr(const stc_cd_reg_map_t *reg_map, uint8_t *data, uint8_t len)
 * @Description: 向data_ptr写入数据
 * @Parameters:  reg_map - 寄存器映射指针
 *               data - 数据
 *               len - 数据长度
 * @Return:      0-失败, 1-成功
 */
static uint8_t cd_can_write_data_to_ptr(const stc_cd_reg_map_t *reg_map, uint8_t *data, uint8_t len)
{
    if (reg_map == NULL || data == NULL || len == 0)
    {
        return 0;
    }
    
    // 特殊寄存器处理
    switch (reg_map->reg_addr)
    {
        case 11: // 复位寄存器
            {
                uint16_t value = (data[0] << 8) | data[1];
                if (value == 1)
                {
                    printf("Chaodian CAN: Reset Command Received\r\n");
                    // 这里可以添加复位逻辑
                    // NVIC_SystemReset();
                }
            }
            break;
            
        case 12: // 恢复出厂设置
            {
                uint16_t value = (data[0] << 8) | data[1];
                if (value == 0xAC52)
                {
                    printf("Chaodian CAN: Factory Reset Command Received\r\n");
                    // 这里可以添加恢复出厂设置逻辑
                    // srv_parm_defaultFactory(1);
                }
                else
                {
                    printf("Chaodian CAN: Invalid Factory Reset Value: 0x%04X\r\n", value);
                    return 0;
                }
            }
            break;
            
        case 13: // 清除用户数据
            {
                uint16_t value = (data[0] << 8) | data[1];
                if (value == 1)
                {
                    printf("Chaodian CAN: Clear User Data Command Received\r\n");
                    // 这里可以添加清除用户数据逻辑
                }
                else
                {
                    printf("Chaodian CAN: Invalid Clear User Data Value: 0x%04X\r\n", value);
                    return 0;
                }
            }
            break;
            
        default:
            // 如果有data_ptr，写入全局变量
            if (reg_map->data_ptr != NULL)
            {
                // 如果有转换函数，使用统一转换函数
                if (reg_map->transform_func != NULL)
                {
                    if (reg_map->transform_func(CD_TRANSFORM_WRITE, reg_map->data_ptr, data, len) == 0)
                    {
                        printf("Chaodian CAN: Write Transform Failed for Reg[%d]\r\n", reg_map->reg_addr);
                        return 0;
                    }
                }
                else
                {
                    // 没有转换函数，直接写入原始数据
                    switch (CD_REG_GET_TYPE(reg_map->flags))
                    {
                        case CD_DATA_TYPE_UINT8:
                            if (len >= 1)
                            {
                                *(uint8_t*)reg_map->data_ptr = data[0];
                            }
                            break;
                            
                        case CD_DATA_TYPE_UINT16:
                            if (len >= 2)
                            {
                                uint16_t value = (data[0] << 8) | data[1];
                                *(uint16_t*)reg_map->data_ptr = value;
                            }
                            break;
                            
                        case CD_DATA_TYPE_UINT32:
                            if (len >= 4)
                            {
                                uint32_t value = ((uint32_t)data[0] << 24) | ((uint32_t)data[1] << 16) | 
                                                ((uint32_t)data[2] << 8) | data[3];
                                *(uint32_t*)reg_map->data_ptr = value;
                            }
                            break;
                            
                        case CD_DATA_TYPE_STRING:
                            {
                                uint8_t reg_count = CD_REG_GET_SIZE(reg_map->flags);
                                uint8_t byte_count = reg_count * 2;  // 寄存器数量 * 2 = 字节数
                                uint8_t copy_len = (len < byte_count) ? len : byte_count;
                                memcpy(reg_map->data_ptr, data, copy_len);
                            }
                            break;
                            
                        default:
                            break;
                    }
                }
            }
            else
            {
                printf("Chaodian CAN: Write Reg[%d] = 0x%04X (No Data Pointer)\r\n", reg_map->reg_addr, (data[0] << 8) | data[1]);
            }
            break;
    }
    
    return 1;
}


/*
 * @Functions:   void cd_can_task(void)
 * @Description: 超电CAN协议主任务函数
 * @Parameters:  NONE
 * @Return:      NONE
 */
void cd_can_task(void)
{
    uint32_t current_tick = drv_systick_getTick();
    
    // 检查多帧传输超时
    if (g_stcCdCan.multi_frame_rx.active)
    {
        if (current_tick - g_stcCdCan.multi_frame_rx.last_update_tick > CD_CAN_MULTI_FRAME_TIMEOUT_MS)
        {
            printf("Chaodian CAN: Multi-frame timeout\r\n");
            g_stcCdCan.multi_frame_rx.active = 0;
            g_stcCdCan.stats.timeout_count++;
        }
    }
    
    // 检查升级超时
    if (g_stcCdCan.upgrade.active)
    {
        if (current_tick - g_stcCdCan.upgrade.last_data_tick > CD_UPGRADE_TIMEOUT_MS)
        {
            printf("Chaodian CAN: Upgrade timeout\r\n");
            g_stcCdCan.upgrade.active = 0;
            g_stcCdCan.upgrade.upgrade_state = CD_UPGRADE_STATE_ERROR;
            g_stcCdCan.stats.timeout_count++;
        }
    }
}

/*
 * @Functions:   static uint8_t cd_can_start_upgrade(uint32_t firmware_size, uint16_t firmware_crc)
 * @Description: 开始升级
 * @Parameters:  firmware_size - 固件大小
 *               firmware_crc - 固件CRC校验
 * @Return:      0-失败, 1-成功
 */
static uint8_t cd_can_start_upgrade(uint32_t firmware_size, uint16_t firmware_crc)
{
    if (firmware_size == 0 || firmware_size > CD_MAX_FIRMWARE_SIZE)
    {
        return 0;
    }
    
    // 初始化升级状态
    memset(&g_stcCdCan.upgrade, 0, sizeof(stc_cd_upgrade_t));
    g_stcCdCan.upgrade.firmware_buffer = g_firmwareBuffer;
    g_stcCdCan.upgrade.buffer_size = CD_MAX_FIRMWARE_SIZE;
    g_stcCdCan.upgrade.firmware_size = firmware_size;
    g_stcCdCan.upgrade.firmware_crc = firmware_crc;
    g_stcCdCan.upgrade.upgrade_state = CD_UPGRADE_STATE_PREPARE;
    g_stcCdCan.upgrade.active = 1;
    g_stcCdCan.upgrade.last_data_tick = drv_systick_getTick();
    
    printf("Chaodian CAN: Upgrade started, Size: %d, CRC: 0x%04X\r\n", firmware_size, firmware_crc);
    
    return 1;
}

/*
 * @Functions:   static uint8_t cd_can_process_upgrade_data(uint8_t *data, uint8_t length)
 * @Description: 处理升级数据
 * @Parameters:  data - 数据
 *               length - 数据长度
 * @Return:      0-失败, 1-成功
 */
static uint8_t cd_can_process_upgrade_data(uint8_t *data, uint8_t length)
{
    if (!g_stcCdCan.upgrade.active || data == NULL || length == 0)
    {
        return 0;
    }
    
    // 检查缓冲区空间
    if (g_stcCdCan.upgrade.received_size + length > g_stcCdCan.upgrade.buffer_size)
    {
        printf("Chaodian CAN: Upgrade buffer overflow\r\n");
        g_stcCdCan.upgrade.upgrade_state = CD_UPGRADE_STATE_ERROR;
        return 0;
    }
    
    // 存储数据
    memcpy(&g_stcCdCan.upgrade.firmware_buffer[g_stcCdCan.upgrade.received_size], data, length);
    g_stcCdCan.upgrade.received_size += length;
    g_stcCdCan.upgrade.last_data_tick = drv_systick_getTick();
    
    // 更新状态
    if (g_stcCdCan.upgrade.upgrade_state == CD_UPGRADE_STATE_PREPARE)
    {
        g_stcCdCan.upgrade.upgrade_state = CD_UPGRADE_STATE_RECEIVE;
    }
    
    // 检查是否接收完成
    if (g_stcCdCan.upgrade.received_size >= g_stcCdCan.upgrade.firmware_size)
    {
        g_stcCdCan.upgrade.upgrade_state = CD_UPGRADE_STATE_VERIFY;
        printf("Chaodian CAN: Firmware received completely, Size: %d\r\n", g_stcCdCan.upgrade.received_size);
    }
    
    return 1;
}

/*
 * @Functions:   static uint8_t cd_can_finish_upgrade(void)
 * @Description: 完成升级
 * @Parameters:  NONE
 * @Return:      0-失败, 1-成功
 */
static uint8_t cd_can_finish_upgrade(void)
{
    if (!g_stcCdCan.upgrade.active)
    {
        return 0;
    }
    
    // 验证固件CRC
    uint16_t calculated_crc = srv_crc16_system(g_stcCdCan.upgrade.firmware_buffer, 
                                              g_stcCdCan.upgrade.received_size, 0);
    
    if (calculated_crc != g_stcCdCan.upgrade.firmware_crc)
    {
        printf("Chaodian CAN: CRC verification failed, Expected: 0x%04X, Calculated: 0x%04X\r\n", 
               g_stcCdCan.upgrade.firmware_crc, calculated_crc);
        g_stcCdCan.upgrade.upgrade_state = CD_UPGRADE_STATE_ERROR;
        return 0;
    }
    
    // CRC验证通过
    g_stcCdCan.upgrade.upgrade_state = CD_UPGRADE_STATE_COMPLETE;
    printf("Chaodian CAN: Upgrade completed successfully\r\n");
    
    // 这里可以添加实际的固件写入逻辑
    // drv_flash_write(g_stcCdCan.upgrade.firmware_buffer, FIRMWARE_ADDR, g_stcCdCan.upgrade.received_size);
    
    return 1;
}

/*
 * @Functions:   static uint8_t cd_can_get_upgrade_state(void)
 * @Description: 获取升级状态
 * @Parameters:  NONE
 * @Return:      升级状态
 */
static uint8_t cd_can_get_upgrade_state(void)
{
    return g_stcCdCan.upgrade.upgrade_state;
}

//----------------------------------------------------------------------------------------
// @Local Functions

/*
 * @Functions:   static void cd_can_process_upgrade_message(uint16_t reg_addr, uint8_t *data)
 * @Description: 处理升级相关消息
 * @Parameters:  reg_addr - 寄存器地址
 *               data - 数据
 * @Return:      NONE
 */
static void cd_can_process_upgrade_message(uint16_t reg_addr, uint8_t *data)
{
    switch (reg_addr)
    {
        case 300: // 开始升级
            {
                uint16_t value = (data[0] << 8) | data[1];
                if (value == 1)
                {
                    printf("Chaodian CAN: Start upgrade command received\r\n");
                    // 这里可以添加开始升级的逻辑
                }
            }
            break;
            
        case 301: // 直接运行app
            {
                uint16_t value = (data[0] << 8) | data[1];
                if (value == 1)
                {
                    printf("Chaodian CAN: Run app command received\r\n");
                    cd_can_finish_upgrade();
                }
            }
            break;
            
        case 302: // 请求进入升级模式
            {
                uint16_t value = (data[0] << 8) | data[1];
                if (value == 1)
                {
                    printf("Chaodian CAN: Enter upgrade mode command received\r\n");
                    // 这里可以添加进入升级模式的逻辑
                }
                else if (value == 2)
                {
                    printf("Chaodian CAN: Exit upgrade mode command received\r\n");
                    g_stcCdCan.upgrade.active = 0;
                    g_stcCdCan.upgrade.upgrade_state = CD_UPGRADE_STATE_IDLE;
                }
            }
            break;
            
        case 303: // 升级包大小
            {
                uint32_t firmware_size = ((uint32_t)data[0] << 24) | ((uint32_t)data[1] << 16) | 
                                        ((uint32_t)data[2] << 8) | data[3];
                printf("Chaodian CAN: Firmware size: %d\r\n", firmware_size);
            }
            break;
            
        case 305: // 升级包CRC校验
            {
                uint16_t firmware_crc = (data[0] << 8) | data[1];
                printf("Chaodian CAN: Firmware CRC: 0x%04X\r\n", firmware_crc);
            }
            break;
            
        case 315: // 下发固件数据
            {
                // 处理固件数据包
                cd_can_process_upgrade_data(data, 4);
            }
            break;
            
        default:
            break;
    }
}


/*
 * @Functions:   static void cd_can_send_multi_frame_data(uint16_t reg_addr, uint16_t reg_count, uint8_t *data, uint16_t data_len, uint8_t func_code)
 * @Description: 发送多帧数据（用于多帧响应）
 * @Parameters:  reg_addr - 寄存器地址
 *               reg_count - 寄存器数量
 *               data - 数据
 *               data_len - 数据长度
 *               func_code - 功能码
 * @Return:      NONE
 */
static void cd_can_send_multi_frame_data(uint16_t reg_addr, uint16_t reg_count, uint8_t *data, uint16_t data_len, uint8_t func_code)
{
    uint8_t frames_needed = (data_len + 3) / 4; // 每帧4字节数据
    uint8_t frame_index;
    uint8_t u8CanBuf[8];
    uint32_t can_id;
    
    for (frame_index = 0; frame_index < frames_needed; frame_index++)
    {
        // 构建CAN ID
        can_id = cd_can_build_id(func_code, reg_addr, CD_DEVICE_ADDR_HOST, g_stcCdCan.device_addr);
        
        // 构建数据
        u8CanBuf[0] = func_code;
        u8CanBuf[1] = (reg_count >> 8) & 0xFF;
        u8CanBuf[2] = reg_count & 0xFF;
        u8CanBuf[3] = frame_index;
        
        // 复制帧数据
        uint16_t frame_data_offset = frame_index * 4;
        uint8_t frame_data_len = 4;
        if (frame_data_offset + frame_data_len > data_len)
        {
            frame_data_len = data_len - frame_data_offset;
        }
        
        memcpy(&u8CanBuf[4], &data[frame_data_offset], frame_data_len);
        
        // 填充剩余字节
        if (frame_data_len < 4)
        {
            memset(&u8CanBuf[4 + frame_data_len], CD_DATA_FILL, 4 - frame_data_len);
        }
        
        // 将数据放入CAN发送队列
        if (g_stccan.vu8canTxMQPushLen < CAN_MAX_TX_SIZE)
        {
            g_stccan.canTxMessage[g_stccan.vu8canTxMQPushLen].ExtId = can_id;
            g_stccan.canTxMessage[g_stccan.vu8canTxMQPushLen].IDE = CAN_ID_EXT;
            g_stccan.canTxMessage[g_stccan.vu8canTxMQPushLen].RTR = CAN_RTRQ_DATA;
            g_stccan.canTxMessage[g_stccan.vu8canTxMQPushLen].DLC = CAN_TX_DLC;
            memcpy(g_stccan.canTxMessage[g_stccan.vu8canTxMQPushLen].Data, &u8CanBuf[0], 8);
            g_stccan.vu8canTxMQPushLen++;
        }
        
        if (g_stccan.vu8canTxMQPushLen >= CAN_MAX_TX_SIZE)
        {
            g_stccan.vu8canTxMQPushLen = 0;
        }
        
        g_stcCdCan.stats.tx_count++;
    }
}

/*
 * @Functions:   uint8_t cd_transform_speed(uint8_t operation, const void *raw_data, uint8_t *data, uint8_t len)
 * @Description: 速度数据转换函数 - 统一的读取转换
 * @Parameters:  operation - 操作类型 (CD_TRANSFORM_READ/CD_TRANSFORM_WRITE)
 *               raw_data - 原始速度数据指针(uint16_t*)
 *               data - 数据缓冲区
 *               len - 数据长度
 * @Return:      读取时返回实际输出的数据长度，写入时返回0-失败, 1-成功
 */
uint8_t cd_transform_speed(uint8_t operation, const void *raw_data, uint8_t *data, uint8_t len)
{
    if (raw_data == NULL || data == NULL || len < 2)
    {
        return 0;
    }
    
    if (operation == CD_TRANSFORM_READ)
    {
        // 读取转换：内部速度值 → 协议格式速度值(km/h*100)
        // 假设内部速度单位为 m/s，需要转换为 km/h*100
        // 转换公式: speed_kmh_100 = speed_ms * 3600 / 1000 * 100 = speed_ms * 360
        
        // 这里假设从GPS模块或其他传感器获取的速度数据
        // 实际实现时需要根据具体的数据源进行调整
        uint16_t speed_ms = *(uint16_t*)raw_data; // 内部速度值，单位：m/s
        
        // 转换为 km/h*100 格式
        uint32_t speed_kmh_100 = (uint32_t)speed_ms * 360;
        
        // 限制速度范围 0-300 km/h (0-30000)
        if (speed_kmh_100 > 30000) speed_kmh_100 = 30000;
        
        data[0] = (speed_kmh_100 >> 8) & 0xFF;
        data[1] = speed_kmh_100 & 0xFF;
        
        return 2;
    }
    else // CD_TRANSFORM_WRITE
    {
        // 5023寄存器为只读，不支持写入
        return 0;
    }
}

/*
 * @Functions:   uint8_t cd_transform_gps_speed_limit(uint8_t operation, const void *raw_data, uint8_t *data, uint8_t len)
 * @Description: GPS上传速度限制转换函数 - 统一的读取和写入转换
 * @Parameters:  operation - 操作类型 (CD_TRANSFORM_READ/CD_TRANSFORM_WRITE)
 *               raw_data - 原始速度限制数据指针(uint16_t*)
 *               data - 数据缓冲区
 *               len - 数据长度
 * @Return:      读取时返回实际输出的数据长度，写入时返回0-失败, 1-成功
 */
uint8_t cd_transform_gps_speed_limit(uint8_t operation, const void *raw_data, uint8_t *data, uint8_t len)
{
    if (raw_data == NULL || data == NULL || len < 2)
    {
        return 0;
    }
    
    if (operation == CD_TRANSFORM_READ)
    {
        // 读取转换：内部速度限制值 → 协议格式速度限制值(km/h*100)
        uint16_t speed_limit_ms = *(uint16_t*)raw_data; // 内部速度限制值，单位：m/s
        
        // 转换为 km/h*100 格式
        uint32_t speed_limit_kmh_100 = (uint32_t)speed_limit_ms * 360;
        
        // 限制速度范围 0-300 km/h (0-30000)
        if (speed_limit_kmh_100 > 30000) speed_limit_kmh_100 = 30000;
        
        data[0] = (speed_limit_kmh_100 >> 8) & 0xFF;
        data[1] = speed_limit_kmh_100 & 0xFF;
        
        return 2;
    }
    else // CD_TRANSFORM_WRITE
    {
        // 写入转换：协议格式速度限制值(km/h*100) → 内部速度限制值
        uint16_t speed_limit_kmh_100 = (uint16_t)((data[0] << 8) | data[1]);
        
        // 限制速度范围 0-300 km/h (0-30000)
        if (speed_limit_kmh_100 > 30000)
        {
            return 0;
        }
        
        // 转换为内部格式 m/s
        // 转换公式: speed_ms = speed_kmh_100 * 1000 / 3600 / 100 = speed_kmh_100 / 360
        uint16_t speed_limit_ms = speed_limit_kmh_100 / 360;
        
        *(uint16_t*)raw_data = speed_limit_ms;
        return 1;
    }
}

// =======================================================================================
// End of file.
// =======================================================================================